<template>
  <div class="table-root">
    <el-table
      :data="userList"
      empty-text="暂无数据"
      :header-cell-style="{ 'background-color': 'rgba(243, 246, 249, 1)' }"
      @selection-change="handleSelectChange"
    >
      <el-table-column align="center" type="selection" />
      <el-table-column align="center" type="index" label="序号" width="60px" />
      <el-table-column
        align="center"
        label="用户名"
        prop="userName"
      ></el-table-column>
      <el-table-column
        align="center"
        label="性别"
        prop="gender"
      ></el-table-column>
      <el-table-column
        align="center"
        label="创建时间"
        prop="createTime"
      ></el-table-column>
      <el-table-column align="center" label="操作" prop="">
        <template #default="scope">
          <el-button type="primary" @click="handleDeleteClick(scope.row)"
            >删除</el-button
          >
          <el-button type="primary" plain @click="handleUpdateClick(scope.row)"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <Page
      :total="totalRef"
      @change-current="handleChangeCurrent"
      @change-size="handleChangeSize"
    ></Page>
  </div>
</template>

<script lang="ts" setup>
import Page from './c-page.vue'
import { deleteBatch, deleteUser, userPage } from '@/api'
import type { UserType } from '@/types'
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'

const $emit = defineEmits(['showDialog'])

const totalRef = ref(0)
const userList = ref<UserType[]>([])

const selectedArr = ref<UserType[]>([])

const searchParam = reactive({
  userName: '',
  gender: '',
  pageNo: 1,
  pageSize: 10
})

const getUserPage = async (param?: any) => {
  searchParam.userName = param?.userName
  searchParam.gender = param?.gender
  const { total, records } = await userPage({
    ...searchParam
  })
  userList.value = records
  totalRef.value = total
}

const reload = () => {
  getUserPage(searchParam)
}
const handleSelectChange = (v: any) => {
  selectedArr.value = v
}

const removeBatch = async () => {
  if (selectedArr.value.length === 0) {
    ElMessage.error('必选选择一条记录')
    return
  }
  const ids = selectedArr.value.map((item) => item.userId)

  await deleteBatch({ userIds: ids })
  ElMessage.success('批量删除成功')
  getUserPage(searchParam)
}

const handleDeleteClick = async (row: any) => {
  await deleteUser(row.userId)
  ElMessage.success('删除成功')
  getUserPage(searchParam)
}

const handleUpdateClick = async (row: any) => {
  $emit('showDialog', { ...row })
}

const handleChangeCurrent = (val: number) => {
  searchParam.pageNo = val
  getUserPage(searchParam)
}

const handleChangeSize = (val: number) => {
  searchParam.pageSize = val
  getUserPage(searchParam)
}

defineExpose({ reload, removeBatch, getUserPage })
getUserPage(searchParam)
</script>

<style lang="scss" scoped>
.table-root {
}
</style>
